package com.lzh.shijicloudstack.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.lzh.shijicloudstack.manager.SysUtilManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;

@Component
public class File_Tools {

    public final static Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);

    // 图片路径
    public static String LOCAL_IMAGE_BASE_URL = System.getProperty("os.name").toLowerCase().contains("windows") ? "F:\\usr\\local\\workspace\\files\\di" : "/usr/local/workspace/files/di";

    /**
     * 用户保存的头像路径
     */
    public static String HEAD_PORTRAIT_BASE_URL = LOCAL_IMAGE_BASE_URL + File.separator + "head_portrait";

    /**
     * 默认文件路径
     */
    public static String DEFAULT_BASE_URL = LOCAL_IMAGE_BASE_URL + File.separator + "base_data";

    /**
     * 默认头像
     */
    public static String DEFAULT_HEAD_PORTRAIT = "default_head_portrait.png";

    /**
     * 下载指定目录下的文件
     *
     * @param basePath 基础路径
     * @param fileName 文件名
     * @param response 响应头
     */
    public static void downloadFile(String basePath, String fileName, HttpServletResponse response) {
        if (StrUtil.isEmpty(fileName) || StrUtil.isEmpty(basePath)) {
            return;
        }

        File file = new File(basePath + File.separator + fileName);
        if (!file.exists()) {
            return;
        }
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition,X-DI-DOWNLOAD");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        try (BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(file.toPath()));) {
            byte[] buff = new byte[1024];
            OutputStream os = response.getOutputStream();
            int i;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 保存图片
     *
     * @param file : 文件
     * @return java.lang.String
     * @author ycx
     * @date 2020/4/17
     */
    public static String uploadFile(MultipartFile file) {

        if (file != null && !file.isEmpty() && file.getOriginalFilename() != null) {
            String fileNamePre = SysUtilManager.getNextId();

            String fileName = fileNamePre + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            try {
                //真实
                SaveFileFromInputStream(file.getInputStream(), LOCAL_IMAGE_BASE_URL + "/" + fileName);

                return fileName;
            } catch (Exception e) {
                logger.error("savePictureError", e.fillInStackTrace());
                return null;
            }
        }
        return null;
    }

    /**
     * 保存头像
     *
     * @param file : 文件
     * @return java.lang.String
     * @author ycx
     * @date 2020/4/17
     */
    public static String uploadHeadPortraitFile(MultipartFile file) {

        if (file != null && !file.isEmpty() && file.getOriginalFilename() != null) {
            String fileNamePre = SysUtilManager.getNextId();

            String fileName = fileNamePre + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            try {
                //真实
                SaveFileFromInputStream(file.getInputStream(), HEAD_PORTRAIT_BASE_URL + File.separator + fileName);
                return fileName;
            } catch (Exception e) {
                logger.error("savePictureError", e.fillInStackTrace());
                return null;
            }
        }
        return null;
    }

    /**
     * 创建文件夹
     *
     * @param filePath : 文件
     * @return java.lang.String
     */
    public File createDir(String filePath) {
        String path = LOCAL_IMAGE_BASE_URL + File.separator + filePath;
        File file = FileUtil.mkdir(path);
        return file;
    }

    /**
     * 保存文件
     *
     * @param stream     : 文件流
     * @param targetPath : 保存路径
     * @author ycx
     * @date 2020/5/7
     */
    public static void SaveFileFromInputStream(InputStream stream, String targetPath)
            throws IOException {
        FileOutputStream outputStream = new FileOutputStream(targetPath);
        int byteCount;
        byte[] bytes = new byte[1024];
        while ((byteCount = stream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, byteCount);
        }
        outputStream.close();
        stream.close();
    }

}
